package cn.ffcs.controller;


import cn.ffcs.result.Result;
import cn.ffcs.utils.FTPUtil;
import cn.ffcs.utils.FtpProcessor;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 1400订阅通知接口
 *
 */
@RestController
@RequestMapping("/VIID/SubscribeNotifications")
@Slf4j
public class SubscribeNotificationsController{

    @Value("${viid_code}")
    private String VIID_CODE;

    @Value("${localFilePath}")
    private String localFilePath;

    @Value("${remoteFilePath}")
    private String remoteFilePath;

    @Value("${failUploadFilePath}")
    private String failUploadFilePath;

    @Resource
    private FtpProcessor ftpProcessor;

    //@Resource
    //private FTPUtil ftpUtil;

    private String ASYNC = "async";
    /**
     * 添加通知
     *
     * @param req
     * @return
     */
    @PostMapping
    public Result saveSubscribeNotification(@RequestBody JSONObject req, String type) {

        JSONArray jsonArray = req.getJSONObject("SubscribeNotificationListObject").getJSONArray("SubscribeNotificationObject");
        long systemTime = System.currentTimeMillis();
        String subscribeType = getSubscribeType(jsonArray.getJSONObject(0));
        String reqStr = req.toString();
        if(subscribeType.equals("empty")) {
            return Result.fail("获取订阅类型失败,写入失败");
        }
        /*
        else if(subscribeType.equals("tollgate")) {
            if(!reqStr.contains("}]}}]}}")){
                reqStr = reqStr.replace("\"TollgateObject\":","\"TollgateObject\":[");
                reqStr = reqStr.replace("}}}]}}", "}]}}]}}");
            }
        } else if(subscribeType.equals("lane")) {
            if(!reqStr.contains("}]},\"Title\"")){
                reqStr = reqStr.replace("\"LaneObject\":","\"LaneObject\":[");
                reqStr = reqStr.replace("}},\"Title\"", "}]},\"Title\"");
            }
        }
         */
         String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String subscribeId = jsonArray.getJSONObject(0).getString("SubscribeID");

        //写入本地文件
        String fileName = systemTime + "_" + subscribeType + "_" + VIID_CODE + "_" + uuid + "_" + subscribeId + ".viid";
        FileWriter writer = null;
        LocalDate date = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String dateStr = date.format(formatter);
        String fileRealPath = localFilePath + "/" + dateStr + "/" +fileName;
        try {

            File path = new File(localFilePath + "/" + dateStr);
            if(!path.exists() && !path.isDirectory()) {
                path.mkdir();
            }
            log.info("写入本地文件:" + fileRealPath);
            writer = new FileWriter(fileRealPath);
            writer.write(reqStr + "\n");
            writer.flush();
            writer.close();

            //Files.copy(new File(localFilePath + "/" + fileName).toPath(), new File(remoteFilePath + "/" + fileName).toPath());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("upload fail: " + fileName);
        }

        if(!ASYNC.equals(type)) {
            //上传ftp服务器
            try {
                InputStream inputStream = new FileInputStream(new File(fileRealPath));
                boolean success = ftpProcessor.uploadToFtp(remoteFilePath, fileName, inputStream);
                inputStream.close();
                if(success) {
                    log.info("上传FTP服务器成功: " + fileName);
                    return Result.succeed("upload success: " + fileName);
                } else {
                    log.error("上传FTP服务器失败: " + fileName);
                    //放入fail文件夹
                    writer = new FileWriter(failUploadFilePath + "/" + fileName);
                    writer.write(reqStr + "\n");
                    writer.flush();
                    writer.close();
                    return Result.fail("upload fail: " + fileName);
                }
            } catch (Exception e) {
                log.error("上传FTP服务器失败: " + fileName);
                e.printStackTrace();
                return Result.fail("upload fail: " + fileName);
            }
        } else {
            log.info("暂不支持异步上传");
        }


        return Result.fail("upload fail: " + fileName);
    }

    public String getSubscribeType(JSONObject subscribeNotificationObject) {
        if(subscribeNotificationObject.containsKey("FaceObjectList")) {
            return "face";
        } else if(subscribeNotificationObject.containsKey("PersonObjectList")) {
            return "person";
        } else if(subscribeNotificationObject.containsKey("MotorVehicleObjectList")) {
            return "vehicle";
        } else if(subscribeNotificationObject.containsKey("DeviceList")) {
            return "ape";
        } else if(subscribeNotificationObject.containsKey("TollgateObjectList")) {
            return "tollgate";
        } else if(subscribeNotificationObject.containsKey("LaneObjectList")){
            return "lane";
        } else if(subscribeNotificationObject.containsKey("CaseObjectList")){
            return "case";
        }
        log.error("获取订阅类型失败:" + subscribeNotificationObject.toString().substring(0,50));
        return "empty";
    }
}
